package com.danciyixue.boot.client.audio.controller;

import com.danciyixue.boot.shared.file.service.impl.MinioFileService;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.InputStream;

/**
 * 客户端音频控制器
 */
@Tag(name = "30. 音频", description = "音频")
@RestController
@ConditionalOnBean(MinioFileService.class)
@RequestMapping("/api/client/v1/audio")
@RequiredArgsConstructor
@Slf4j
public class DcyxAudioController {

    private final MinioFileService minioFileService;

    /**
     * 获取单词音频
     *
     * @param word 单词
     * @return 音频文件流
     */
    @GetMapping("/{word}")
    @Operation(summary = "获取单词音频")
    public ResponseEntity<InputStreamResource> getWordAudio(
            @Parameter(description = "单词") @PathVariable String word) {
        try {
            // 构建音频文件名
            String audioFileName = word.toLowerCase() + ".mp3";
            
            // 获取音频文件流
            InputStream audioStream = minioFileService.getFileStream("audio", audioFileName);
            
            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType("audio/mpeg"));
            headers.setContentDispositionFormData("attachment", audioFileName);
            
            // 返回文件流
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(new InputStreamResource(audioStream));
        } catch (Exception e) {
            log.error("获取单词音频失败: {}", word, e);
            return ResponseEntity.notFound().build();
        }
    }
}
